package com.cell.api.application.netty.client;

import com.cell.api.application.constants.Command;
import com.cell.api.application.netty.code.Packet;
import com.cell.api.application.netty.coder.PacketDecoder;
import com.cell.api.application.netty.coder.PacketEncoder;
import com.cell.api.application.netty.utils.NumberUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;

/**
 * <p>
 * 客户端
 * </p>
 *
 * @author zdy
 * @date 2021/11/8
 */
public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        // 首先，netty通过ServerBootstrap启动服务端
        Bootstrap client = new Bootstrap();
        //第1步 定义线程组，处理读写和链接事件，没有了accept事件
        EventLoopGroup group = new NioEventLoopGroup();
        client.group(group);
        //第2步 绑定客户端通道
        client.channel(NioSocketChannel.class);
        //第3步 给NIoSocketChannel初始化handler， 处理读写事件
        client.handler(new ChannelInitializer<NioSocketChannel>() {  //通道是NioSocketChannel
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                //字符串解编码器，一定要加在SimpleClientHandler 的上面
                ch.pipeline().addLast(new PacketEncoder());
                ch.pipeline().addLast(new PacketDecoder());
                ch.pipeline().addLast(new DelimiterBasedFrameDecoder(
                        Integer.MAX_VALUE, Delimiters.lineDelimiter()[0]));
                //找到他的管道 增加他的handler
                ch.pipeline().addLast(new SimpleClientHandler());
            }
        });
        //连接服务器
        //ChannelFuture future = client.connect("8.134.52.171", 8090).sync();
        ChannelFuture future = client.connect("127.0.0.1", 8090).sync();
        //发送数据给服务器
        Packet packet = new Packet();
        packet.setGetCommand(Command.HEART_BEAT);
        byte[] bytes = NumberUtils.deToHexString(170).getBytes();
        packet.setDataLength(bytes.length);
        packet.setBytes(bytes);
        future.channel().writeAndFlush(packet);
        //当通道关闭了，就继续往下走
        future.channel().closeFuture().sync();
    }


}
